const balanceApi = require('../../api/balance.js')

Page({
  data: {
    loading: false,
    records: [],
    currentPage: 1,
    pageSize: 20,
    hasMore: true,
    
    // 筛选条件
    statusOptions: [
      { value: '', name: '全部状态' },
      { value: 1, name: '成功' },
      { value: 0, name: '处理中' },
      { value: -1, name: '失败' }
    ],
    statusIndex: 0,
    startDate: '',
    endDate: '',
    today: '',
    
    // 统计信息
    statistics: null,
    
    // 弹窗
    showDetailModal: false,
    selectedRecord: null
  },

  onLoad() {
    this.checkLoginStatus()
    this.initData()
    this.loadRecords()
    this.loadStatistics()
  },

  // 检查登录状态
  checkLoginStatus() {
    const app = getApp()
    console.log('检查登录状态:', {
      isLogin: app.globalData.isLogin,
      userInfo: app.globalData.userInfo,
      token: app.globalData.token
    })

    if (!app.globalData.isLogin) {
      wx.showModal({
        title: '提示',
        content: '请先登录后查看充值记录',
        showCancel: false,
        success: () => {
          wx.redirectTo({
            url: '/pages/auth/login/login'
          })
        }
      })
      return false
    }
    return true
  },

  // 初始化数据
  initData() {
    const today = new Date()
    const todayStr = this.formatDate(today)
    
    // 默认查询最近30天
    const thirtyDaysAgo = new Date(today.getTime() - 30 * 24 * 60 * 60 * 1000)
    const startDateStr = this.formatDate(thirtyDaysAgo)
    
    this.setData({
      today: todayStr,
      startDate: startDateStr,
      endDate: todayStr
    })
  },

  // 加载充值记录
  async loadRecords(reset = false) {
    if (this.data.loading) return
    
    // 检查登录状态
    if (!this.checkLoginStatus()) {
      return
    }
    
    this.setData({ loading: true })
    
    try {
      const currentPage = reset ? 1 : this.data.currentPage
      const params = {
        page: currentPage,
        size: this.data.pageSize
      }
      
      // 只有当状态不为空字符串时才添加状态参数
      const selectedStatus = this.data.statusOptions[this.data.statusIndex].value
      if (selectedStatus !== '') {
        params.status = selectedStatus
      }
      
      // 添加时间范围参数
      if (this.data.startDate) {
        params.startTime = this.data.startDate + ' 00:00:00'
      }
      if (this.data.endDate) {
        params.endTime = this.data.endDate + ' 23:59:59'
      }

      console.log('开始加载充值记录，参数:', params)
      const result = await balanceApi.getRechargeRecords(params)
      console.log('充值记录API响应:', result)

      // result 直接是 data 部分，不需要检查 success
      if (result && result.records) {
        const newRecords = result.records.map(record => ({
          ...record,
          createTime: this.formatDateTime(record.createTime),
          updateTime: this.formatDateTime(record.updateTime),
          rechargeAmount: this.formatAmount(record.rechargeAmount),
          beforeBalance: this.formatAmount(record.beforeBalance),
          afterBalance: this.formatAmount(record.afterBalance),
          statusName: this.getStatusName(record.status),
          rechargeTypeName: this.getRechargeTypeName(record.rechargeType),
          paymentMethodName: this.getPaymentMethodName(record.paymentMethod)
        }))

        if (reset) {
          this.setData({
            records: newRecords,
            currentPage: 1,
            hasMore: newRecords.length >= this.data.pageSize
          })
        } else {
          this.setData({
            records: [...this.data.records, ...newRecords],
            currentPage: currentPage,
            hasMore: newRecords.length >= this.data.pageSize
          })
        }
      } else {
        // 没有数据时设置空数组
        if (reset) {
          this.setData({
            records: [],
            currentPage: 1,
            hasMore: false
          })
        }
      }
    } catch (error) {
      console.error('加载充值记录失败:', error)
      wx.showToast({
        title: error.message || '加载失败',
        icon: 'none'
      })
    } finally {
      this.setData({ loading: false })
    }
  },

  // 加载统计信息
  async loadStatistics() {
    // 检查登录状态
    if (!this.checkLoginStatus()) {
      return
    }
    
    try {
      const result = await balanceApi.getRechargeStatistics()
      // result 直接是 data 部分
      if (result) {
        this.setData({
          statistics: {
            totalAmount: this.formatAmount(result.totalAmount),
            totalCount: result.totalCount || 0,
            successRate: result.successRate || 0
          }
        })
      }
    } catch (error) {
      console.error('加载统计信息失败:', error)
    }
  },

  // 状态变化
  onStatusChange(e) {
    this.setData({
      statusIndex: e.detail.value
    })
  },

  // 开始日期变化
  onStartDateChange(e) {
    this.setData({
      startDate: e.detail.value
    })
  },

  // 结束日期变化
  onEndDateChange(e) {
    this.setData({
      endDate: e.detail.value
    })
  },

  // 搜索记录
  searchRecords() {
    this.loadRecords(true)
  },

  // 重置筛选条件
  resetFilter() {
    this.setData({
      statusIndex: 0,
      startDate: '',
      endDate: ''
    }, () => {
      this.loadRecords(true)
    })
  },

  // 加载更多
  loadMore() {
    if (!this.data.hasMore || this.data.loading) return
    
    this.setData({
      currentPage: this.data.currentPage + 1
    }, () => {
      this.loadRecords()
    })
  },

  // 查看记录详情
  viewRecordDetail(e) {
    const record = e.currentTarget.dataset.record
    this.setData({
      selectedRecord: record,
      showDetailModal: true
    })
  },

  // 关闭详情弹窗
  closeDetailModal() {
    this.setData({
      showDetailModal: false,
      selectedRecord: null
    })
  },

  // 复制订单号
  copyOrderNo(e) {
    const orderNo = e.currentTarget.dataset.order
    wx.setClipboardData({
      data: orderNo,
      success: () => {
        wx.showToast({
          title: '订单号已复制',
          icon: 'success'
        })
      }
    })
  },

  // 跳转到充值页面
  goToRecharge() {
    wx.navigateTo({
      url: '/pages/recharge/recharge'
    })
  },

  // 格式化日期
  formatDate(date) {
    const year = date.getFullYear()
    const month = (date.getMonth() + 1).toString().padStart(2, '0')
    const day = date.getDate().toString().padStart(2, '0')
    return `${year}-${month}-${day}`
  },

  // 格式化日期时间
  formatDateTime(timeStr) {
    if (!timeStr) return ''
    const date = new Date(timeStr)
    const year = date.getFullYear()
    const month = (date.getMonth() + 1).toString().padStart(2, '0')
    const day = date.getDate().toString().padStart(2, '0')
    const hour = date.getHours().toString().padStart(2, '0')
    const minute = date.getMinutes().toString().padStart(2, '0')
    const second = date.getSeconds().toString().padStart(2, '0')
    return `${year}-${month}-${day} ${hour}:${minute}:${second}`
  },

  // 格式化金额
  formatAmount(amount) {
    if (!amount && amount !== 0) return '0.00'
    return parseFloat(amount).toFixed(2)
  },

  // 获取状态名称
  getStatusName(status) {
    const statusMap = {
      1: '成功',
      0: '处理中',
      '-1': '失败'
    }
    return statusMap[status] || '未知'
  },

  // 获取充值类型名称
  getRechargeTypeName(type) {
    const typeMap = {
      'MANUAL': '手动充值',
      'AUTO': '自动充值',
      'ADMIN': '管理员充值'
    }
    return typeMap[type] || type || '手动充值'
  },

  // 获取支付方式名称
  getPaymentMethodName(method) {
    const methodMap = {
      'BALANCE': '余额支付',
      'WECHAT': '微信支付',
      'ALIPAY': '支付宝',
      'SIMULATION': '模拟支付'
    }
    return methodMap[method] || method || '余额支付'
  },

  // 下拉刷新
  onPullDownRefresh() {
    this.loadRecords(true).finally(() => {
      wx.stopPullDownRefresh()
    })
  },

  // 触底加载更多
  onReachBottom() {
    this.loadMore()
  },

  // 页面显示时检查登录状态
  onShow() {
    const app = getApp()
    if (app.globalData.isLogin && this.data.records.length === 0) {
      // 如果已登录但没有数据，重新加载
      this.loadRecords(true)
      this.loadStatistics()
    }
  }
}) 